﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using CSP.Model.CSP;
using System.Collections.ObjectModel;
using CSP.Model.CSPEnum;

namespace CSP.Web.Service
{
    public partial class Detail : CSPMainPageBase
    {

        private string _pageTitle;

        private string _pageKeyWords;

        private string _pageDescription;

        private string _contactPhone;

        /// <summary>
        /// 页面title 
        /// </summary>
        protected string PageTitle
        {
            get
            {
                if (ViewState["pagetitle"] != null)
                {
                    return ViewState["pagetitle"].ToString();
                }
                if (_pageTitle != null)
                {
                    ViewState["pagetitle"] = _pageTitle;
                }
                return _pageTitle;
            }
        }

        /// <summary>
        /// 页面关键字
        /// </summary>
        protected string PageKeyWords
        {
            get
            {
                if (ViewState["pagekeywords"] != null)
                {
                    return ViewState["pagekeywords"].ToString();
                }

                if (_pageKeyWords != null)
                {
                    ViewState["pagekeywords"] = _pageKeyWords;
                }
                return _pageKeyWords;
            }
        }

        /// <summary>
        /// 页面描述
        /// </summary>
        protected string PageDescription
        {
            get
            {
                if (ViewState["pagedescription"] != null)
                {
                    return ViewState["pagedescription"].ToString();
                }

                if (_pageDescription != null)
                {
                    ViewState["pagedescription"] = _pageDescription;
                }
                return _pageDescription;
            }
        }

        /// <summary>
        /// 联系预约电话
        /// </summary>
        protected string ContactPhone
        {
            get 
            {
                if (ViewState["contactphone"]!=null)
                {
                    return ViewState["contactphone"].ToString();
                }

                if (_contactPhone!=null)
                {
                    ViewState["contactphone"] = _contactPhone;
                }
                return _contactPhone;
            }    
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            PageInit();
        }

        private void PageInit()
        {
            if (Request["id"] == null)
            {
                LoggerProvider.Error("请求的Id不存在/service/detail.aspx");
                this.FailRedirect("您请求的课程信息不存在", "/");
            }

            ServiceInfo serviceInfo = GetServiceInfoById(Convert.ToInt32(Request["id"].ToString()));
            if (serviceInfo == null)
            {
                LoggerProvider.Error("请求的课程不存在" + Request["id"].ToString() + "/service/detail.aspx");
                this.FailRedirect("您请求的课程信息不存在", "/");
            }

            BindServiceInfoUI(serviceInfo);
            BindContactWayUI(serviceInfo.username);
            BindAuthenticationUI(serviceInfo.username);

            if (!IsPostBack)
            {
                BindRateListUIByServiceId(serviceInfo.id);    
            }
            

            //相关推荐
            BindRecommendInfoUI();

            this.U_ServiceShopInfo.UserName = serviceInfo.username;
            this.U_AppointmentRecord.ServiceId = serviceInfo.id;
        }

        private void BindServiceInfoUI(CSP.Model.CSP.ServiceInfo serviceInfo)
        {
            this.LB_Title.Text = serviceInfo.title;
            _pageTitle = serviceInfo.title;

            if (string.IsNullOrWhiteSpace(serviceInfo.Description))
            {
                _pageDescription = serviceInfo.title;
            }
            else
            {
                _pageDescription = serviceInfo.Description;
            }

            _pageKeyWords = serviceInfo.KeyWords;
            this.LB_OriginalPrice.Text = serviceInfo.OriginalPrice.Value.ToString("0.00") + "元/" + serviceInfo.PriceUnit.name;
            this.LB_PriceUnit.Text = serviceInfo.OriginalPriceUnit.name;
            this.LB_Price.Text = serviceInfo.Price.ToString("0.00");
            decimal spareMoney = serviceInfo.OriginalPrice.Value - serviceInfo.Price;

            if((PriceType)serviceInfo.PriceType==PriceType.FixedPrice)//一口价
            {
                //节省
                if (spareMoney <= 0)
                {
                    this.L_OriginalPrice.Visible = false;

                }
                else
                {
                    this.LB_SaveMoney.Text = (spareMoney).ToString("0.00");
                }    
            }
            else if ((PriceType)serviceInfo.PriceType == PriceType.PriceRange)//价格范围
            {
                this.L_OriginalPrice.Visible = false;
                this.LB_Price.Text = serviceInfo.PriceStart.ToString("0.00") + "--" + serviceInfo.PriceEnd.ToString("0.00");
                this.LB_SaveMoney.Text = (spareMoney).ToString("0.00");
            }
            else if ((PriceType)serviceInfo.PriceType == PriceType.Negotiable)//面议
            {
                this.L_OriginalPrice.Visible = false;
                this.LB_Price.Text = "面 议";
                this.LB_SaveMoney.Text = (spareMoney).ToString("0.00");
            }

            this.LinkType.InnerText = serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceType.Name;
            this.LinkType.Title= serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceType.Name;
            this.LinkType.HRef = "/search/st"+serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId.ToString()+"/";
            this.LB_SurplusEnjoyCount.Text = serviceInfo.SurplusEnjoyCount.ToString();
            this.LB_ClassOfMemberNumber.Text = serviceInfo.ClassOfMemberNumber.ToString();
            this.LB_AgeStart.Text = serviceInfo.AgeStart.ToString();
            this.LB_AgeEnd.Text = serviceInfo.AgeEnd.ToString();
            this.LB_Province.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_Province;
            this.Link_Province.HRef = "/search/st" + serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId.ToString() + "-sa" + serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Province.ToString() + "/";
            this.Link_Province.Title = this.LB_Province.Text;
            this.LB_City.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_City;
            this.Link_City.HRef = "/search/st" + serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId.ToString() + "-sa" + serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.City.ToString() + "/";
            this.Link_City.Title = this.LB_City.Text;
            this.LB_County.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.CN_County;
            this.Link_County.HRef = "/search/st" + serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId.ToString() + "-sa" + serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.County.ToString() + "/";
            this.Link_County.Title = this.LB_County.Text;
            this.LB_Street.Text = serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Street;


            this.DIV_Content.InnerHtml = serviceInfo.Content;
            this.LB_ServiceType.Text = GetServiceTypeByServiceTypeId(serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId);
            this.LB_ClassType.Text = GetClassTypeByClassTypeId(serviceInfo.ClassTypeId);
            this.LB_ClassValidityStart.Text = serviceInfo.ClassValidityStart.ToString("yyyy-MM-dd");
            this.LB_ClassValidityEnd.Text = serviceInfo.ClassValidityEnd.ToString("yyyy-MM-dd");
            this.LB_Privilege.Text = this.LB_SaveMoney.Text;
            this.LB_ReservationNum.Text = (serviceInfo.EnjoyCount.Value - serviceInfo.SurplusEnjoyCount).ToString();
            string zoom= serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Maps.ToArray()[0].Zoom.ToString();
            string centerPointX= serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Maps.ToArray()[0].CenterPointX.ToString();
            string centerPointY= serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Maps.ToArray()[0].CenterPointY.ToString();
            string markerPointX= serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Maps.ToArray()[0].MarkerPointX.ToString();
            string markerPointY= serviceInfo.ServiceInfoAddressRels.ToArray()[0].Address.Maps.ToArray()[0].MarkerPointY.ToString();
            this.LookForMap.HRef = "javascript:CustomMap.MapShow(" + zoom + "," + centerPointX + "," + centerPointY + "," + markerPointX + "," + markerPointY + ")";
            if (!string.IsNullOrWhiteSpace(serviceInfo.Phone))
            {
                this.Div_Phone.Visible = true;
                this.LB_Phone.Text = _contactPhone = serviceInfo.Phone;
                this.R_ContactWay.Visible = false;
            }
            else
            {
                this.Div_Phone.Visible = false;
            }
            ServiceImage[] serviceImages = serviceInfo.ServiceImages.OrderBy(s=>s.OrderId).ToArray();
            for (int i = 0; i < serviceImages.Length; i++)
            {
                string imgUrl = serviceImages[i].FilePath + "S_" + serviceImages[i].FileName;
                if (i == 0)
                {
                    this.Img_Head.Src = imgUrl;
                    this.Img_Head.Alt = serviceInfo.title;
                    this.Img_Head.Attributes.Add("title",serviceInfo.title);
                    this.Img_Head1.Src = imgUrl;
                    this.Img_Head1.Attributes.Add("title", serviceInfo.title);
                    this.Img_Head1.Alt = serviceInfo.title;
                }
                else if (i == 1)
                {
                    this.Img_Head2.Src = imgUrl;
                    this.Img_Head2.Attributes.Add("title", serviceInfo.title);
                    this.Img_Head2.Alt = serviceInfo.title;
                }
                else if (i == 2)
                {
                    this.Img_Head3.Src = imgUrl;
                    this.Img_Head3.Attributes.Add("title", serviceInfo.title);
                    this.Img_Head3.Alt = serviceInfo.title;
                }
                else if (i == 3)
                {
                    this.Img_Head4.Src = imgUrl;
                    this.Img_Head4.Attributes.Add("title", serviceInfo.title);
                    this.Img_Head3.Alt = serviceInfo.title;
                }
                else if (i == 4)
                {
                    this.Img_Head5.Src = imgUrl;
                    this.Img_Head5.Attributes.Add("title", serviceInfo.title);
                    this.Img_Head5.Alt = serviceInfo.title;
                }
            }
        }


        /// <summary>
        /// 绑定证书
        /// </summary>
        private void BindAuthenticationUI(string userName)
        {
            IEnumerable<CSP.Model.CSP.Authentication> certificates = GetCertificate(userName);

            this.R_Authentication.DataSource = certificates;
            this.R_Authentication.DataBind();
        }

        /// <summary>
        /// 绑定联系方式
        /// </summary>
        private void BindContactWayUI(string userName)
        {
            ICollection<Model.CSP.ContactWay> contactWays = GetContactWaysByUser(userName);
            if (contactWays == null)
            {
                contactWays = new Collection<Model.CSP.ContactWay>();
            }
            this.R_ContactWay.DataSource = contactWays;
            this.R_ContactWay.DataBind();
        }

        /// <summary>
        /// 绑定相关推荐
        /// </summary>
        /// <param name="searchServiceList"></param>
        private void BindRecommendInfoUI()
        {
            //string[] strIds = Txt_RecommendIds.Value.Split(',');
            //List<int> ids = (from id in strIds
            //                 select Convert.ToInt32(id)).ToList();
            SearchServiceList[] searchServiceList = GetDataByIds(RecommendType.RecommendRelated, 6);
            this.R_ServiceInfo.DataSource = searchServiceList;
            this.R_ServiceInfo.DataBind();
        }


        /// <summary>
        /// 获取推荐数据
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SearchServiceList[] GetDataByIds(RecommendType recommendType, int count)
        {
            SearchServiceList[] result;
            using (var recommendBll = CSPBllFactory.GetInstance().GetRecommendBll())
            {
                result = recommendBll.GetSearchServiceListByRecommendTypeAndCount(recommendType, count,"detail"+Request.QueryString["id"]);
            }
            return result;
        }

        private List<SearchServiceList> GetSearchServiceListByIdsDefault(List<int> ids, int pageIndex, int pageSize)
        {
            List<SearchServiceList> result;
            using (var serviceInfoBll = CSPBllFactory.GetInstance().GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataByIdsDefault(ids, pageIndex, pageSize);
            }
            return result;
        }

        private ICollection<Model.CSP.ContactWay> GetContactWaysByUser(string userName)
        {
            ICollection<Model.CSP.ContactWay> result = null;
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            using (IContactWayBll contactWayBll = factory.GetContactWayBll())
            {
                result = contactWayBll.FindByUser(userName);
            }

            return result;
        }

        /// <summary>
        /// 根据Id获取服务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private CSP.Model.CSP.ServiceInfo GetServiceInfoById(int id)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceInfo result = null;
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                result = serviceInfoBll.GetDataById(id);
            }
            return result;
        }

        //private string GetNameByServiceAreaId(int serviceAreaId)
        //{
        //    CSPBllFactory factory = CSPBllFactory.GetInstance();
        //    ServiceArea serviceArea = null;
        //    using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
        //    {
        //        serviceArea = serviceAreaBll.GetDataById(serviceAreaId);
        //    }
        //    return serviceArea.Name;
        //}

        /// <summary>
        /// 从Bll层根据ParentId获取ServiceTypes
        /// </summary>
        /// <returns></returns>
        private string GetServiceTypeByServiceTypeId(int serviceTypeId)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            ServiceType serviceType = null;
            using (IServiceTypeBll serviceTypeBll = bllFactory.GetServiceTypeBll())
            {
                serviceType = serviceTypeBll.GetDataById(serviceTypeId);
            }
            return serviceType.Name;
        }

        private string GetClassTypeByClassTypeId(int classTypeId)
        {
            ClassType classType = new ClassType();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IClassTypeBll classTypeBll = bllFactory.GetClassTypeBll())
            {
                classType = classTypeBll.GetDataById(classTypeId);
            }
            return classType.Name;
        }

        /// <summary>
        /// 绑定评价列表UI
        /// </summary>
        /// <returns></returns>
        private void BindRateListUIByServiceId(int serviceInfoId)
        {
            U_CSPRateListBindByRateBusinessType(serviceInfoId, UserControls.RateList.RateListType.FromService);
            //U_CSPRateList.RateListBind();

        }


        /// <summary>
        /// 绑定评价列表用户控件 通过评价业务类型
        /// </summary>
        /// <param name="rateBusinessType"></param>
        private void U_CSPRateListBindByRateBusinessType(int serviceInfoId, UserControls.RateList.RateListType rateBusinessType)
        {
            U_CSPRateList.ServiceId = serviceInfoId;
            U_CSPRateList.RateBusinessType = rateBusinessType;
            U_CSPRateList.RateListBind();
        }

        /// <summary>
        /// 根据认证类型和认证状态获取 当前认证名称
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetCNNameByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "企业认证";
            }

            if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "个人认证";
            }

            return "未认证";
        }

        /// <summary>
        /// 获取样式根据企业认证和个人认证 状态
        /// </summary>
        /// <param name="personalAuthentication"></param>
        /// <param name="enterpriseAuthentication"></param>
        /// <returns></returns>
        protected string GetStyleByAuthentication(int personalAuthentication, int enterpriseAuthentication)
        {
            //企业认证
            if ((AuthenticationStatus)enterpriseAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-enterprise";
            }

            //个人认证
            if ((AuthenticationStatus)personalAuthentication == AuthenticationStatus.Accomplish)
            {
                return "i-v-personal";
            }

            return "";
        }


        /// <summary>
        /// 获取证书信息
        /// </summary>
        private IEnumerable<CSP.Model.CSP.Authentication> GetCertificate(string userName)
        {
            ICollection<CSP.Model.CSP.Authentication> result = null;
            CSPBllFactory _authenticationFactory = CSPBllFactory.GetInstance();
            using (IAuthenticationBll authenticationBll = _authenticationFactory.GetAuthenticationBll())
            {
                result = authenticationBll.GetByUser(userName);
            }
            if (result == null)
            {
                result = new Collection<CSP.Model.CSP.Authentication>();
            }

            return result.Where(c => c.CertificateType != 1 && c.CertificateType != 0);

        }

        /// <summary>
        /// 获取联系方式链接字符串
        /// </summary>
        /// <param name="address">API 的地址</param>
        /// <param name="contactType">0旺旺,1QQ</param>
        /// <param name="urlType">0图片，1URL</param>
        /// <returns></returns>
        protected string GetContactURL(string address, int contactType, int urlType)
        {
            string result = "";
            if (contactType == 0 && urlType == 0)
            {
                result = CSP.Common.Tools.CommonTool.GetTaoBaoContactImgURL(address);
            }
            else if (contactType == 0 && urlType == 1)
            {
                result = CSP.Common.Tools.CommonTool.GetTaoBaoContactURL(address);
            }
            else if (contactType == 1 && urlType == 0)
            {
                result = CSP.Common.Tools.CommonTool.GetQQContactImgURL(address);
            }
            else if (contactType == 1 && urlType == 1)
            {
                result = CSP.Common.Tools.CommonTool.GetQQContactURL(address);
            }

            return result;
        }

        /// <summary>
        /// 根据价格类型，现价格，最低价格，最高价格，获取价格
        /// </summary>
        /// <param name="priceType"></param>
        /// <param name="price"></param>
        /// <param name="priceStart"></param>
        /// <param name="priceEnd"></param>
        /// <returns></returns>
        protected string GetPriceByPriceTypeAndPriceAndPriceStartAndPriceEnd(int priceType, decimal price, decimal priceStart, decimal priceEnd)
        {
            string result = "";
            if ((PriceType)priceType == PriceType.FixedPrice) //一口价
            {
                result = price.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.PriceRange)//价格范围
            {
                result = priceStart.ToString("0.00") + "--" + priceEnd.ToString("0.00");
            }
            else if ((PriceType)priceType == PriceType.Negotiable)//面议
            {
                result = "面议";
            }
            return result;
        }

    }
}